package com.zm.zmgz.interceptorzm;

import com.alibaba.fastjson.JSON;
import com.zm.zmgz.annotationzm.LoginRequired;
import com.zm.zmgz.pojo.Response;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Objects;

public class AuthorityInterceptor extends HandlerInterceptorAdapter { // 权限拦截器

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // ①:START 方法注解级拦截器
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解，需要认证
        if (methodAnnotation != null) {
            // 这写你拦截需要干的事儿，比如取缓存，SESSION，权限判断等
            ServletContext servletContext = request.getServletContext();
            String token = request.getHeader("X-Token");
            String sessionId = request.getSession().getId();
            System.out.println("sessionId验证:"+sessionId);
            String s = (String) servletContext.getAttribute(token); // 通过用户名获取当前合法sessionID
//            String s2 = (String) servletContext.getAttribute("440229199310244219");
//            System.out.println("s2:"+s2);
            System.out.println("当前该用户的合法sessionID:"+s);
            if(Objects.isNull(s) || s != sessionId){ // 如果不存在合法的sessionID或合法的sessionID不等于本次sessionID,判断为未登录或登录已注销
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-Type", "application/json");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Methods", "GET, POST");
//                response.setHeader("Access-Control-Allow-Origin", "*"); 添加该设置后,用户重新登录后,旧页面无法正常退出系统
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer=null;
                try {
                    System.out.println("请重新登录!");
                    writer=response.getWriter();
                    writer.write(JSON.toJSONString(new Response(50008,"请重新登录!")));
                    writer.flush();
                } catch (IOException ex) {
//                    logger.error(ex.getMessage());
                }finally {
                    if(writer!=null) {
                        writer.close();
                    }
                }
                return false;
            }
            return true;
        }
        return true;
    }
}
